/**
 * Copyright (c) 2010-2011 julewa.com.  
 * All rights reserved. 
 * 
 * @author Huang Benhua
 * @date 2011-2-20
 * 
 **/
package com.julewa.loading;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.dispatcher.mapper.ActionMapping;
import org.apache.struts2.dispatcher.mapper.DefaultActionMapper;

import com.opensymphony.xwork2.config.ConfigurationManager;

//
public class RESTNameMapper extends DefaultActionMapper {
	public static final String URI_ROOT = "$URI";
	public static final String REST_STRING = "$REST";
	public static final String RESTS = "$RESTS";
	static String DEFAULT_ACTION_NAME = SystemUtils.getProperty("system.uri.default", "index");
	public ActionMapping getMapping(HttpServletRequest request, ConfigurationManager configManager){
        String uri = request.getServletPath();
        StringBuffer pre = new StringBuffer();
        if(uri.equals("/")){
        	uri = DEFAULT_ACTION_NAME;
        }else if(uri.endsWith("/")){
        	uri = uri.substring(1, uri.length() - 1);
        	pre.append("../");
        }else{
        	uri = uri.substring(1);
        }
        //
        RESTActionMapping mapping = new RESTActionMapping();
    	mapping.setParam("$URI", uri);
        char c, lc = '/';
        int lastidx = 0, restidx = -1, restinc = 1;
        for(int i = 0; i < uri.length(); ++i){
        	c = uri.charAt(i);
        	switch(c){
	        	case '/':{
        			pre.append("../");
	        		if(lc == '/'){//意味着rest消息
	        			if(restidx < 0){
	        				restidx = lastidx;//但是此时此刻却有不同
	        				restinc = 2;
	        			}
	        		}
        			lastidx = i;
	        	}break;
	        	default:{
	        		if(restidx >= 0)continue;
	        		if(lc != '/')break;
	        		if((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')){
	        			break;
	        		}
	        		restidx = lastidx;
	        	}
        	}
        	lc = c;
        }
        //
        request.setAttribute(URI_ROOT, pre == null?"":pre.toString());
        if(restidx > 0){
        	mapping.setRest(request, uri.substring(restidx + restinc));
        	uri = uri.substring(0, restidx);
        }else if(restidx == 0){
        	mapping.setRest(request, uri.substring(restinc)); 
        	uri = "";
        }
        lastidx = uri.lastIndexOf('/');
        if(lastidx > 0){
        	mapping.setNamespace("/" + uri.substring(0, lastidx));
        	uri = uri.substring(lastidx + 1);
        }
        if("".equals(uri)){
        	mapping.setName(DEFAULT_ACTION_NAME);
        }else{
        	mapping.setName(uri);
        }
        return mapping;
    }

}
